package cn.kgc.tangcco.tcbd1011.no13.customer.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.kgc.tangcco.tcbd1011.no13.base.util.JDBCUtils;
import cn.kgc.tangcco.tcbd1011.no13.customer.dao.CustomerDao;
import cn.kgc.tangcco.tcbd1011.no13.customer.entity.Customer;

public class CustomerDaoImpl implements CustomerDao {

	private QueryRunner queryRunner;
	public CustomerDaoImpl() {
		queryRunner = new QueryRunner(JDBCUtils.getDataSource());
				
	}
	@Override
	public int addCustomer(Customer customer) {
		try {
			return this.queryRunner.update("insert into customer value(default,?,?,?,?,?,?)",customer.getCustomerName(),customer.getAge(),customer.getGender(),customer.getIDCard(),customer.getCustomerNum(),customer.getAddress());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int updateCustomer(Customer customer) {
		try {
			return this.queryRunner.update("update customer set customerName=?,age=?,gender=?,IDCard=?,customerNum=?,address=? where customerId=?",customer.getCustomerName(),customer.getAge(),customer.getGender(),customer.getIDCard(),customer.getCustomerNum(),customer.getAddress(),customer.getCustomerId());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int deleteCustomer(int pk) {
		try {
			return this.queryRunner.update("delete from customer where customerId=?",pk);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public List<Customer> queryAllCustomer(Customer customer) {
		try {
			return this.queryRunner.query("select * from customer order by customerId desc", new BeanListHandler<>(Customer.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Customer detailCustomer(int pk) {
		try {
			return this.queryRunner.query("select * from customer where customerId=?", new BeanHandler<>(Customer.class),pk);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return null;
	}

	@Override
	public int queryCountCustomer() {
		try {
			return this.queryRunner.query("select count(*) from customer", new ScalarHandler<>());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

}
